package com.szly.phm.common.utils;

import com.szly.phm.common.entity.vo.permissiom.PermissionTreeVO;

import java.util.ArrayList;
import java.util.List;

public class MenuTree {
    private List<PermissionTreeVO> menuList = new ArrayList<PermissionTreeVO>();
    public MenuTree(List<PermissionTreeVO> menuList) {
        this.menuList=menuList;
    }

    //建立树形结构
    public List<PermissionTreeVO> builTree(){
        List<PermissionTreeVO> treeMenus =new  ArrayList<PermissionTreeVO>();
        for(PermissionTreeVO menuNode : getRootNode()) {
            menuNode=buildChilTree(menuNode);
            treeMenus.add(menuNode);
        }
        return treeMenus;
    }

    //递归，建立子树形结构
    private PermissionTreeVO buildChilTree(PermissionTreeVO pNode){
        List<PermissionTreeVO> chilMenus =new  ArrayList<PermissionTreeVO>();
        for(PermissionTreeVO menuNode : menuList) {
            if(menuNode.getPermissionPid()!=null&&menuNode.getPermissionPid().equals(pNode.getId())) {
                chilMenus.add(buildChilTree(menuNode));
            }
        }
        pNode.setPermissionTreeVOList(chilMenus);
        return pNode;
    }

    //获取根节点
    private List<PermissionTreeVO> getRootNode() {
        List<PermissionTreeVO> rootMenuLists =new  ArrayList<PermissionTreeVO>();
        for(PermissionTreeVO menuNode : menuList) {
            if(menuNode.getPermissionPid()==null) {
                rootMenuLists.add(menuNode);
            }
        }
        return rootMenuLists;
    }
}
